package com.sugon.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.dao.ModuleSpPurchasingBatchDao;
import com.sugon.dao.ModuleSpStockDao;
import com.sugon.entity.FactoryTypeEntity;
import com.sugon.entity.ModuleSpEntity;
import com.sugon.entity.ModuleSpPurchasingBatchEntity;
import com.sugon.modules.excel.dto.MoldPurchaseBatchImportParamDTO;
import com.sugon.modules.mold.consts.MoldSpStockState;
import com.sugon.service.FactoryTypeService;
import com.sugon.service.ModuleSpPurchasingBatchService;
import com.sugon.service.ModuleSpService;
import com.sugon.utils.Constant;
import com.sugon.utils.ShiroUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模具型芯备件采购批次信息Service实现类
 *
 * @author sugon
 * @date 2021-10-13 09:58:53
 */
@Service("moduleSpPurchasingBatchService")
public class ModuleSpPurchasingBatchServiceImpl implements ModuleSpPurchasingBatchService {
    @Resource
    private ModuleSpPurchasingBatchDao moduleSpPurchasingBatchDao;
    @Resource
    private ModuleSpPurchasingBatchService moduleSpPurchasingBatchService;
    @Resource
    private ModuleSpStockDao moduleSpStockDao;
    @Resource
    private ModuleSpService moduleSpService;
    @Resource
    private FactoryTypeService factoryTypeService;

    /**
     * 试试计算采购批次库存状态
     *
     * @return
     */
    @Override
    public boolean realtimePurchasingBacthStockState() {
        List<Map<String, Object>> purchasingBatchStockStateStatList = moduleSpStockDao.statPurchasingBatchStockState();
        if (CollectionUtil.isNotEmpty(purchasingBatchStockStateStatList)) {
            Map<String, ModuleSpPurchasingBatchEntity> tem = new HashMap<>();
            ModuleSpPurchasingBatchEntity moduleSpPurchasingBatch;
            // 设置本次需要更新的型芯批次信息
            for (Map<String, Object> purchasingBatchStockStateStat : purchasingBatchStockStateStatList) {
                String purchasingBatchId = MapUtil.getStr(purchasingBatchStockStateStat, "PURCHASING_BATCH_ID");
                Integer state = MapUtil.getInt(purchasingBatchStockStateStat, "STATE");
                Integer stateNum = MapUtil.getInt(purchasingBatchStockStateStat, "STATENUM");
                moduleSpPurchasingBatch = tem.get(purchasingBatchId);
                if (moduleSpPurchasingBatch == null) {
                    moduleSpPurchasingBatch = new ModuleSpPurchasingBatchEntity(purchasingBatchId);
                    tem.put(purchasingBatchId, moduleSpPurchasingBatch);
                }
                if (MoldSpStockState.ED.equals(state)) {
                    moduleSpPurchasingBatch.setStockInNum(stateNum);
                } else if (MoldSpStockState.USED.equals(state)) {
                    moduleSpPurchasingBatch.setStockOutNum(stateNum);
                }
            }
            // 更新状态
            Collection<ModuleSpPurchasingBatchEntity> values = tem.values();
            for (ModuleSpPurchasingBatchEntity value : values) {
                moduleSpPurchasingBatchService.update(value);
            }
        }
        return true;
    }

    /**
     * 根据唯一码查询模具型芯采购批次信息
     *
     * @param moldSparePartsUniqueCode 模具型芯备件唯一码
     * @return
     */
    @Override
    public ModuleSpPurchasingBatchEntity queryBySpUniqueCode(String moldSparePartsUniqueCode) {
        /*
            厂家 型芯代码 批次   件号
            CTS 0440    202201-2
         */
        int lastIndexOf = moldSparePartsUniqueCode.lastIndexOf("-");
        Assert.isTrue(lastIndexOf >= 0, "型芯备件码必须含有'-'，请确认！");
        // 获取采购批次码并查询对应的批次信息
        String barCord = moldSparePartsUniqueCode.substring(0, lastIndexOf);
        Map<String, Object> param = new HashMap<>();
        param.put("barCord", barCord);
        List<ModuleSpPurchasingBatchEntity> purchasingBatchList = queryList(param);
        return CollectionUtil.isNotEmpty(purchasingBatchList) ? purchasingBatchList.get(0) : null;
    }

    /**
     * 查询
     *
     * @param id 主键
     * @return
     */
    @Override
    public ModuleSpPurchasingBatchEntity queryObject(String id) {
        return moduleSpPurchasingBatchDao.queryObject(id);
    }

    /**
     * @param map 参数
     * @return
     */
    @Override
    public List<ModuleSpPurchasingBatchEntity> queryList(Map<String, Object> map) {
        return moduleSpPurchasingBatchDao.queryList(map);
    }

    /**
     * 查询数据数
     *
     * @param map 参数
     * @return
     */
    @Override
    public int queryTotal(Map<String, Object> map) {
        return moduleSpPurchasingBatchDao.queryTotal(map);
    }

    /**
     * 保存
     *
     * @param moduleSpPurchasingBatch 实体
     * @return
     */
    @Override
    public int save(ModuleSpPurchasingBatchEntity moduleSpPurchasingBatch) {
        moduleSpPurchasingBatch.setId(RandomUtil.randomString(32));
        moduleSpPurchasingBatch.setDelFlag(Constant.IS_NOT_DEL_INT);
        moduleSpPurchasingBatch.setGmtCreate(DateUtil.date());
        moduleSpPurchasingBatch.setCreateUser(ShiroUtils.getUserId());
        moduleSpPurchasingBatch.setStockInNum(0);
        moduleSpPurchasingBatch.setStockOutNum(0);
        return moduleSpPurchasingBatchDao.save(moduleSpPurchasingBatch);
    }

    /**
     * 更新
     *
     * @param moduleSpPurchasingBatch 实体
     * @return
     */
    @Override
    public int update(ModuleSpPurchasingBatchEntity moduleSpPurchasingBatch) {
        moduleSpPurchasingBatch.setGmtModified(DateUtil.date());
        moduleSpPurchasingBatch.setModifyUser(ShiroUtils.getUserId());
        return moduleSpPurchasingBatchDao.update(moduleSpPurchasingBatch);
    }

    /**
     * 批量删除
     *
     * @param id
     * @return
     */
    @Override
    public int delete(String id) {
        return moduleSpPurchasingBatchDao.delete(id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(String[] ids) {
        return moduleSpPurchasingBatchDao.deleteBatch(ids);
    }

    /**
     * 导入模具批量仓欧信息
     *
     * @param excelInputStream
     * @return
     * @throws Exception
     */
    @Override
    public int importMoldPurchaseBatchData(InputStream excelInputStream) throws Exception {
        // 获取导入配置
        ImportParams importParams = getImportParams();
        // 从上传文件中读取叉车台账列表
        List<MoldPurchaseBatchImportParamDTO> moldPurchaseBatchList = ExcelImportUtil.importExcel(excelInputStream, MoldPurchaseBatchImportParamDTO.class, importParams);
        if (CollectionUtil.isEmpty(moldPurchaseBatchList)) {
            return 0;
        }
        // 本次导入数据行数
        int importRows = 0;
        ModuleSpPurchasingBatchEntity purchasingBatch;
        for (MoldPurchaseBatchImportParamDTO batchData : moldPurchaseBatchList) {
            // 厂家代码和型芯条码代码必填
            if (!StrUtil.isAllNotEmpty(batchData.getFactorySelfCode(), batchData.getUniqueBarCode())) {
                continue;
            }
            // 校验厂家子编码是否有效
            FactoryTypeEntity factoryType = factoryTypeService.queryBySelfCode(batchData.getFactorySelfCode());
            if (factoryType == null) {
                continue;
            }
            // 校验型芯条码代码是否有效
            ModuleSpEntity moduleSpInDB = moduleSpService.queryByUniqueBarCode(batchData.getUniqueBarCode());
            if (moduleSpInDB == null) {
                continue;
            }
            purchasingBatch = new ModuleSpPurchasingBatchEntity();
            purchasingBatch.setSupplierId(factoryType.getId());
            purchasingBatch.setMoldSpId(moduleSpInDB.getId());
            purchasingBatch.setUnitPrice(batchData.getUnitPrice());
            purchasingBatch.setBeginMonth(batchData.getBeginMonth());
            purchasingBatch.setEndMonth(batchData.getEndMonth());
            purchasingBatch.setBarCordAnalysisRule(StrUtil.format("{}{}({})", factoryType.getSelfCode(), moduleSpInDB.getUniqueBarCode(), com.sugon.modules.utils.DateUtil.getMonthRangeStr(batchData.getBeginMonth(), batchData.getEndMonth())));
            importRows += save(purchasingBatch);
            purchasingBatch = null;
        }
        return importRows;
    }

    /**
     * 设置导入参数
     *
     * @return
     */
    private ImportParams getImportParams() {
        ImportParams params = new ImportParams();
        params.setKeyIndex(0);
        return params;
    }
}
